//
//  ForumViewController.m
//  一键车讯
//
//  Created by Scott on 14/10/27.
//  Copyright (c) 2014年 lanou.3g.com. All rights reserved.
//

#import "ForumViewController.h"
#import "ForumDetailController.h"
#import "PersonalViewController.h"
#import "SearchViewController.h"
#import "NetHandler.h"
#import "Forum.h"
#import "ForumCell.h"
#import "UIImageView+WebCache.h"
#import "AIMTableViewIndexBar.h"
#import "NetHandler.h"
#import "ForumCar.h"
#import "ForumChildrenViewController.h"
#import "MJRefresh.h"

@interface ForumViewController ()<UITableViewDataSource, UITableViewDelegate, AIMTableViewIndexBarDelegate>

// 热门
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UITableView *hotTableView;
@property (nonatomic, retain) UISegmentedControl *segment;
@property (nonatomic, assign) int countx;
// 车系
@property (nonatomic, retain) NSMutableArray *arrRow;
@property (nonatomic, retain) NSMutableArray *arrSection;
@property (nonatomic, retain) NSMutableDictionary *dict;
//@property (nonatomic, retain) UITableView *carTableView;
@property (nonatomic, retain) NSMutableArray *childremArr;
@property (nonatomic, retain) AIMTableViewIndexBar *aim;
@property (nonatomic, retain) NSMutableArray *arrImage;

@property (nonatomic, retain) ForumCar *forumCar;
@end

@implementation ForumViewController

// 初始化
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        // 热门
        self.arr = [NSMutableArray array];
        
        self.hotTableView = [[UITableView alloc] init];
        [self.view addSubview:self.hotTableView];
        [_hotTableView release];
        
        // 车系
        self.arrRow = [NSMutableArray array];
        self.arrSection = [NSMutableArray array];
        self.dict = [NSMutableDictionary dictionary];
        self.childremArr = [NSMutableArray array];
        
    }
    return self;
}


// 内存管理
- (void)dealloc
{
    [_hotTableView release];
    [_arr release];
    [self.segment release];
//    [_carTableView release];
    [_childremArr release];
    [_arrRow release];
    [_arrSection release];
    [_arrImage release];
    [_dict release];
    [_aim release];
    [super dealloc];
}


- (void)startData
{
    // 解析热门页面数据
    self.title = @"论坛";
    NSString *str = @"http://mrobot.pcauto.com.cn/v3/bbs/hot?pageNo=1&pageSize=20";
    [NetHandler networkWithURL:str completion:^(id result) {
        
        NSMutableArray *dicsArr = [result objectForKey:@"topicList"];

        for (NSDictionary *dic in dicsArr) {
            Forum *forum = [[Forum alloc] initWithDictionary:dic];
            [self.arr addObject:forum];
//            [forum release];
        }
        [self setupRefresh];
        [self.hotTableView reloadData];
    }];
    
    
    // 解析车系页面数据
    NSString *str1 = @"http://mrobot.pcauto.com.cn/v3/bbs/pcauto_v2_bbs_forum_tree";
    [NetHandler networkWithURL:str1 completion:^(id result) {
        
        // 定义一个数组来接收整个车系的整个数组
        NSMutableArray *arrCar = [[[result objectForKey:@"children"] objectAtIndex:0] objectForKey:@"children"];
        
        // 将车系的整个数组保存起来， 下一步将在这个数组中进行查询
        self.childremArr = arrCar;
        
//        NSLog(@"%@", self.childremArr);
        
        
        // 遍历整个数组
        for (NSDictionary *dic in arrCar) {
            
            NSMutableArray *arr = [dic objectForKey:@"me"];
            
            NSString *str1 = [arr objectAtIndex:1];
            
            NSRange range = [str1 rangeOfString:@" "];
            
            // 取出的是（A，B，C....Z)
            str1 = [str1 substringToIndex:(range.location)];
//            NSLog(@"----====-----%@", str1);
            // 将（A，B，C...Z)写入到数组里
            int flag = 1;
            for (int i = 0; i < self.arrSection.count && flag == 1; i++) {
                if ([str1 isEqualToString:self.arrSection[i]]) {
                    flag = 0;
                }
            }
            if (flag == 1) {
                [self.arrSection addObject:str1];
            }
        }
        
//        NSLog(@"=====----=====%@", self.arrSection);
        
//        self.arrImage = [NSMutableArray array];
        
        for (int i = 0; i < self.arrSection.count; i++) {
            self.arrRow = [NSMutableArray array];
//            self.arrImage = [NSMutableArray array];
            
            for (NSDictionary *dic in arrCar) {
                self.forumCar = [[ForumCar alloc] init];
                
                NSMutableArray *arr = [dic objectForKey:@"me"];
                
                // 字符串接收车系名
                NSString *str = [arr objectAtIndex:1];
                
                // 车系编号
                self.forumCar.num = [arr objectAtIndex:0];
                
                // 车系的logo
                self.forumCar.pic = [arr objectAtIndex:2];
                
                if ([str hasPrefix:self.arrSection[i]]) {
                    NSRange range = [str rangeOfString:@" "];
                    str = [str substringFromIndex:(range.location + range.length)];
                   
                    // 找到的车系的名字
                    self.forumCar.name = str;
                    [self.arrRow addObject:self.forumCar];
                }
            }
            [self.dict setValue:self.arrRow forKey:self.arrSection[i]];
            //NSLog(@"%@", self.dict);
//            NSLog(@"%@", self.dict);
        }
        [self.hotTableView reloadData];
    }];
}


- (void)setupViews
{
    // 热门
    self.hotTableView.frame = CGRectMake(0, 104, self.view.frame.size.width - 30, self.view.frame.size.height - 104);
    _hotTableView.dataSource = self;
    _hotTableView.delegate = self;
    [self.view addSubview:self.hotTableView];
//    [_hotTableView release];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 索引条
    self.aim = [[AIMTableViewIndexBar alloc] init];
    self.aim.frame = CGRectMake(300, 110, 20, self.view.frame.size.height - 120);
    self.aim.backgroundColor = [UIColor clearColor];
    self.aim.delegate = self;
    self.aim.layer.hidden = YES;
    [self.view addSubview:self.aim];
//    [_aim release];
    
    // 车系
//    self.carTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height - 104) style:UITableViewStylePlain];
//    _carTableView.dataSource = self;
//    _carTableView.delegate = self;
//    [self.view addSubview:self.carTableView];
//    [_carTableView release];
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self startData];
    [self setupViews];
    
    // UINavigationController
    // 是否透明
    self.navigationController.navigationBar.translucent = YES;
    // 取消返回箭头
//    self.automaticallyAdjustsScrollViewInsets = YES;
    
    // UINavigationItem

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(barLeftButtonItemAction:)] autorelease];
    
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-gerenzhongxin-2.png"] style:UIBarButtonItemStyleDone target:self action:@selector(barRightButtonItemAction:)] autorelease];

    // UISegmentedControl
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"热门", @"车系"]];
    self.segment.frame = CGRectMake(0, 64, 320, 40);
    self.segment.selectedSegmentIndex = 0;
    self.segment.backgroundColor = [UIColor whiteColor];
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segment];
    [_segment release];
  

    
}

//UINavigationItem方法
- (void)barLeftButtonItemAction:(UIBarButtonItem *)barButton
{
    // 返回首页
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

    
    



- (void)barRightButtonItemAction:(UIBarButtonItem *)barButton
{
    // 推出个人中心页面
    PersonalViewController *person = [[PersonalViewController alloc] init];
    [self.navigationController pushViewController:person animated:YES];
    [person release];
    NSLog(@"个人中心");
}


// UISegmentedControl方法
- (void)segmentAction:(UISegmentedControl *)segment
{
    // 一个sitch..case语句，条件：选择分段空间的下标
    // 当为0时，即选择热门,将索引条隐藏
    // 当为1时，即选择车系,将索引条显示
    switch (self.segment.selectedSegmentIndex) {
        case 0:
            self.aim.layer.hidden = YES;
            [self.hotTableView reloadData];
            break;
        case 1:
            self.aim.layer.hidden = NO;
            [self.hotTableView reloadData];
            break;
        default:
            break;
    }
}

#pragma mark UItableView协议方法
// 返回多少个Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.segment.selectedSegmentIndex == 0) {
        return 1;
    } else {
        
        // 第三方
        [self.aim setIndexes:self.arrSection];
        return self.arrSection.count;
    }
}


// 返回 Sections的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

    if (self.segment.selectedSegmentIndex == 0) {
        return 0;
    } else {
        return self.arrSection[section];
    }
}


// 返回 对应的section有多少个元素，也就是多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.segment.selectedSegmentIndex == 0) {
        //NSLog(@"jgrgioarwe  %d", [self.arr count]);
        return [self.arr count];
    } else {
        NSMutableArray *arr = [self.dict objectForKey:[self.arrSection objectAtIndex:(section)]];
        return arr.count;
    }
}


// 返回指定的row的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segment.selectedSegmentIndex == 0) {
        static NSString *str = @"reuse";
        ForumCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[[ForumCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
        }
        Forum *forum = [self.arr objectAtIndex:indexPath.row];
        cell.titleLabel.text = forum.title;
        cell.forum = forum;
        return cell;
    } else {
        static NSString *str1 = @"reuse1";
        ForumCar *forum = [[self.dict objectForKey:[self.arrSection objectAtIndex:(indexPath.section)]] objectAtIndex:indexPath.row];
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str1];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str1] autorelease];
        }
        cell.textLabel.text = forum.name;
        [cell.imageView setImageWithURL:[NSURL URLWithString:forum.pic]];
       return cell;
        
    }
}

// Cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

 //推出论坛详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segment.selectedSegmentIndex == 0) {
        ForumDetailController *forumDetailVC = [[ForumDetailController alloc] init];
        forumDetailVC.forum = [self.arr objectAtIndex:indexPath.row]; // 2.将要传的值给第一步创建的属性
        //NSLog(@"%@", forumDetailVC.forum.topicId);
        [self.navigationController pushViewController:forumDetailVC animated:YES];
        [forumDetailVC release];
    } else {

        // 判断点击的cell对应的车系的id号。根据这个id号在childArr中找到最终的数组。
        ForumCar *forum = [[self.dict objectForKey:[self.arrSection objectAtIndex:(indexPath.section)]] objectAtIndex:indexPath.row];
        
//        NSLog(@"%@", forum.num);
        
        for (NSDictionary *dic in self.childremArr) {
            
            NSArray *arr = [dic objectForKey:@"me"];
            NSString *str = arr[0];
            
            // 判断ID号是否相同，如果相同，将children数组取出来。再从数组中将具体的名字遍历处理，传给第二个页面
            if (str == forum.num) {
                
                NSArray *childrenDetailArr = [dic objectForKey:@"children"];
    
                // 将车系下面的具体名字放入一个新的具体数组中
            
                NSMutableArray *childName = [NSMutableArray array];
                
                for (NSDictionary *dic in childrenDetailArr) {
                    
                    NSArray *arr = [dic objectForKey:@"me"];
                    
//                    NSString *name = arr[1];
                    
                    [childName addObject:arr];
                    
                }
                
            // 将childName数组传值给第二个界面，（通过属性传值即可）
                
                ForumChildrenViewController *chVC = [[ForumChildrenViewController alloc] init];
                
                chVC.childName = childName;
                
                [self.navigationController pushViewController:chVC animated:YES];
            }
        }
    }
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.hotTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.hotTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.hotTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.hotTableView footerEndRefreshing];
    //
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    //self.hotTableView.headerPullToRefreshText = @"准备刷新...";
    self.hotTableView.headerReleaseToRefreshText = @"松开即可刷新...";
    self.hotTableView.headerRefreshingText = @"正在刷新...";
    
    self.hotTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.hotTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.hotTableView.footerRefreshingText = @"加载中";
    
    self.countx = 2;
    NSLog(@"se.countx %d", self.countx);
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.hotTableView reloadData];
        
        [_hotTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.hotTableView headerEndRefreshing];
    });
}

- (void)footerRereshing
{
    //_dataSource = [[NSMutableArray alloc]init];
    
    //    self.countx += 1;
    //http://mrobot.pcauto.com.cn/v3/bbs/hot?pageNo=1&pageSize=20
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/hot?pageNo=%d&pageSize=20", self.countx];
    [NetHandler networkWithURL:str completion:^(id result) {
        
        NSMutableArray *dicsArr = [result objectForKey:@"topicList"];
        
        for (NSDictionary *dic in dicsArr) {
            Forum *forum = [[Forum alloc] initWithDictionary:dic];
            [self.arr addObject:forum];
            //            [forum release];
        }
        [self.hotTableView reloadData];
        
    }];
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.hotTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.hotTableView footerEndRefreshing];
        _countx += 1;
        NSLog(@"self.countx %d", self.countx);
    });
    
}

#pragma mark AIMTableViewIndexBarDelegate

// 第三方自带方法。
- (void)tableViewIndexBar:(AIMTableViewIndexBar *)indexBar didSelectSectionAtIndex:(NSInteger)index
{
    if ([self.hotTableView numberOfSections] > index && index > -1) {
        [self.hotTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
